利用 ggplot2 套件繪圖

郭耀仁

2017-12-09

ggplot2

載入 tidyversegapminder

library(tidyverse)
library(gapminder)

The best stats you’ve ever seen

https://youtu.be/jbkSRLYSojo

相關:數值 vs. 數值

ggplot() + geom_point() 繪製散佈圖

gapminder_2007 <- gapminder %>%
  filter(year == 2007)
scatter <- ggplot(gapminder_2007, aes(x = gdpPercap, y = lifeExp)) +
  geom_point()

顯示散佈圖

scatter

aes() 中加入 color =

scatter <- ggplot(gapminder_2007, aes(x = gdpPercap, y = lifeExp, color = continent)) +
  geom_point()

不同的洲別有不同的顏色

scatter

log_scale

scatter <- ggplot(gapminder_2007, aes(x = gdpPercap, y = lifeExp, color = continent)) +
  geom_point() +
  scale_x_log10()

顯示 log 數值

scatter

線圖:時間 vs. 數值

ggplot() + geom_line() 繪製線圖

gapminder_tw <- gapminder %>%
  filter(country == "Taiwan")
line <- ggplot(gapminder_tw, aes(x = year, y = lifeExp)) +
  geom_line()

顯示線圖

line

多個線條

gapminder_na <- gapminder %>%
  filter(country %in% c("China", "Hong Kong, China", "Japan", "Korea, Rep.", "Taiwan"))
multi_lines <- ggplot(gapminder_na, aes(x = year, y = lifeExp, color = country)) +
  geom_line()

顯示多組線圖

multi_lines

散佈

ggplot() + geom_histogram() 繪製直方圖

hist <- ggplot(gapminder_2007, aes(x = lifeExp)) +
  geom_histogram(bins = 40)

顯示直方圖

hist

ggplot() + geom_boxplot() 繪製盒鬚圖

box <- ggplot(gapminder_2007, aes(x = continent, y = lifeExp)) +
  geom_boxplot()

顯示盒鬚圖

box

直方圖加入 facet_wrap()

multi_hists <- ggplot(gapminder_2007, aes(x = lifeExp, fill = continent)) +
  geom_histogram(bins = 20) +
  facet_wrap(~continent, nrow = 2)

顯示多個直方圖

multi_hists

排名(類別 vs. 數值)

垂直長條圖 ggplot() + geom_bar(stat = "identity")

gapminder_2007_na <- gapminder_2007 %>%
  filter(country %in% c("China", "Hong Kong, China", "Japan", "Korea, Rep.", "Taiwan"))
barv <- ggplot(gapminder_2007_na, aes(x = country, y = gdpPercap)) +
  geom_bar(stat = "identity")

顯示垂直長條圖

barv

水平長條圖 + coord_flip()

barh <- ggplot(gapminder_2007_na, aes(x = country, y = gdpPercap)) +
  geom_bar(stat = "identity")+ 
  coord_flip()

顯示水平長條圖

barh

在一個畫布上畫多個圖形

  • 使用 gridExtra 套件來幫忙
  • grid.arrange() 函數
install.packages("gridExtra")
library(gridExtra)

gg1 <- ggplot(gapminder_2007_na, aes(x = country, y = gdpPercap)) +
  geom_bar(stat = "identity")
gg2 <- ggplot(gapminder_2007_na, aes(x = country, y = gdpPercap)) +
  geom_bar(stat = "identity")+ 
  coord_flip()

顯示網格畫布

grid.arrange(gg1, gg2, nrow = 2)

ggplotly() 加入互動性

  • 使用 plotly 套件的 ggplotly() 函數
install.packages("plotly")
library(plotly)
static_gg <- ggplot(gapminder_2007, aes(x = gdpPercap, y = lifeExp, color = continent)) +
  geom_point() +
  scale_x_log10()

顯示 ggplotly 圖形

ggplotly(static_gg)

R 語言的互動性解法

Plotly + Shiny App

Gapminder Replica

如何做出來

R 語言動態視覺化的 Hello World - 利用 RSelenium、plotly 與 shiny 模仿 Hans Rosling 的視覺化大作

ggplot2 文件

http://docs.ggplot2.org/current/index.html